extends Area2D
class_name Bullet

# 子弹属性
var speed: float = 300.0
var direction: Vector2 = Vector2.UP
var is_player_bullet: bool = true
var damage: int = 1

# 子弹纹理
var bullet_textures = {
	Vector2.UP: preload("res://assets/Images/Bullet/Bullet(UP).png"),
	Vector2.DOWN: preload("res://assets/Images/Bullet/Bullet(DOWN).png"),
	Vector2.LEFT: preload("res://assets/Images/Bullet/Bullet(LEFT).png"),
	Vector2.RIGHT: preload("res://assets/Images/Bullet/Bullet(RIGHT).png")
}

# 节点引用
@onready var sprite = $Sprite2D
@onready var collision_shape = $CollisionShape2D
@onready var lifetime_timer = $LifetimeTimer

# 信号
signal bullet_hit(hit_pos: Vector2, is_player_bullet: bool)

func _ready():
	# 设置碰撞形状
	var shape = RectangleShape2D.new()
	shape.size = Vector2(8, 8)
	collision_shape.shape = shape
	
	# 连接信号
	area_entered.connect(_on_area_entered)
	body_entered.connect(_on_body_entered)
	lifetime_timer.timeout.connect(_on_lifetime_timeout)
	
	# 设置初始纹理
	update_sprite()

func _physics_process(delta):
	# 移动子弹
	position += direction * speed * delta

func update_sprite():
	if direction in bullet_textures:
		sprite.texture = bullet_textures[direction]

func _on_area_entered(area):
	# 处理与区域的碰撞
	var parent = area.get_parent()
	if parent is EnemyTank and is_player_bullet:
		# 玩家子弹击中敌人
		parent.take_damage()
		bullet_hit.emit(position, is_player_bullet)
		queue_free()
	elif parent is Player and not is_player_bullet:
		# 敌人子弹击中玩家
		parent.take_damage()
		bullet_hit.emit(position, is_player_bullet)
		queue_free()
	elif parent is StaticBody2D:
		# 击中墙壁
		bullet_hit.emit(position, is_player_bullet)
		queue_free()

func _on_body_entered(body):
	# 处理与静态体的碰撞（墙壁等）
	if body is StaticBody2D:
		bullet_hit.emit(position, is_player_bullet)
		queue_free()

func _on_lifetime_timeout():
	# 子弹生命周期结束
	queue_free()
